﻿using pdfer.FileObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace pdfer.PdfObjecs
{
    internal class ToUnicodeDictionary: PdfFileObject
    {

    }

    internal class CMapObject
    {

        public CMapObject()
        {

        }

        /// <summary>
        /// <0000> <FFFF>
        /// </summary>
        public List<(Int32 start, Int32 end, Int32 count)> CodeSpaceRange { get; set; } = [];
        public Dictionary<Int32, Byte[]> BFChar { get; set; } = [];
        public List<(Int32 Start, Int32 End, Int32 uStart)> BFRange { get; set; } = [];
        public List<(Int32 Start, Int32 End, Byte[][] uStart)> BFRange2 { get; set; } = [];

        public String GetString(ReadOnlySpan<Byte> data)
        {
            var sb = new StringBuilder();
            for(var i = 0; i < data.Length; i++)
            {
                Int32 charData = data[i];
                var c = 0;
                var xx = 0123;
                while (true)
                {
                    c++;
                    if (CodeSpaceRange.Any(p => charData >= p.start && charData <= p.end && c >= p.count))
                    {
                        break;
                    }
                    i++;
                    if (i >= data.Length)
                    {
                        break;
                    }
                    charData = data[i] | (charData << 8);
                }

                //var hexStr = charData.ToString("X");
                if(BFChar.TryGetValue(charData, out var target))
                {
                    sb.Append(Encoding.Unicode.GetString(target));
                }
                else
                {
                    var bf = BFRange.Where(p => charData >= p.Start && charData <= p.End).FirstOrDefault();
                    if (bf == default)
                    {
                        var bf2 = BFRange2.Where(p => charData >= p.Start && charData <= p.End).FirstOrDefault();
                        if (bf2 == default)
                        {
                            if (charData < Byte.MaxValue)
                            {
                                sb.Append(Encoding.ASCII.GetString([(Byte)charData]));
                            }
                            else
                            {
                                sb.Append(Encoding.Unicode.GetString(BitConverter.GetBytes(charData)));
                            }
                        }
                        else
                        {
                            sb.Append(bf2.uStart[charData - bf2.Start]); 
                        }
                    }
                    else
                    {
                        sb.Append(bf.uStart);
                    }
                }
            }
            return sb.ToString();
        }
    }
}
